package br.unifor.cct.mia.comunication.server;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import br.unifor.cct.mia.comunication.comum.Config;
import br.unifor.cct.mia.comunication.comum.InputData;


public abstract class AbstractServer extends Thread {
	
	private ServerSocket serverSocket = null;
	
	public AbstractServer() {
		try {
			this.serverSocket = new ServerSocket(Config.serverPort);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	@Override
	public void run() {

		while ( !serverSocket.isClosed() ) {
			try {
				Socket client = serverSocket.accept();
				ObjectInputStream input = new ObjectInputStream(client.getInputStream());
				ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
				
				InputData inputData = (InputData)input.readObject();				
				Double result = evaluate(inputData);			
				
				output.writeObject(result);				
				client.close();
			}
			catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}		
	}
	
	protected abstract Double evaluate(InputData inputData)throws FileNotFoundException, IOException, InterruptedException;
}